package com.atguigu.spzx.gateway.filter;

import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class SpzxLoginAuthGlobalFilter implements GlobalFilter , Ordered {
    @Resource
    RedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        AntPathMatcher matcher = new AntPathMatcher();
        boolean match = matcher.match("/api/**/auth/**", path);
        if(!match){
            //1 路径格式不满足上面的直接放行
            return chain.filter(exchange);
        }
        //2、如果路径满足/api/**/auth/** 格式 进行登录校验
        //获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        if(!StringUtils.isEmpty(token)){
            if(redisTemplate.hasKey("user:login:"+token)){
                //2.1 已登录 放行请求
                //请求头包含token 并且token在redis中有登录成功的状态信息 代表已登录 放行请求
                return chain.filter(exchange);
            }
        }
        //2.2 未登录 返回一个需要登录的result对象设置到响应体内
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add("content-type" , MediaType.APPLICATION_JSON_UTF8_VALUE);
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("code" , 205);
        jsonObject.addProperty("message" , "需要登录");
        String toString = jsonObject.toString();
        Mono<DataBuffer> mono = Mono.just(response.bufferFactory().wrap(toString.getBytes()));
        return response.writeWith(mono);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
